<?php

declare (strict_types=1);

namespace app\common\model\store\shop;

use cores\BaseModel;
use think\db\Query;
use think\facade\Cache;
use think\model\relation\BelongsTo;

/**
 * 商家门店店员模型
 * Class Clerk
 * @package app\common\model\store
 */
class Clerk extends BaseModel
{
    // 定义表名
    protected $name = 'store_shop_clerk';

    // 定义主键
    protected $pk = 'clerk_id';

    public static ?int $shopShopId;

    protected bool $isGlobalScopeShopId = false;
    /**
     * 定义全局的查询范围
     * @param Query $query
     */
    public function scopeStore_id(Query $query)
    {
        $shopShopId = self::getShopId();
        $shopShopId > 0 && $query->where($query->getTable() . '.shop_shop_id', $shopShopId);
    }

    /**
     * 获取当前操作的商户ID
     * @return int|null
     */
    private static function getShopId(): ?int
    {
        if (empty(self::$shopShopId)) {
            self::$shopShopId = app()->request->shopId();
        }
        $info = app()->request->header("Access-Token");
        if(!$info){
            return 0;
        }
        $cache = Cache::get(app()->request->header("Access-Token"));
        if(isset($cache['user']['shop_id']) && !self::$shopShopId && $info){
            self::$shopShopId = (Cache::get(app()->request->header("Access-Token")))['user']['shop_id'];
        }
        return self::$shopShopId;
    }

    /**
     * 关联用户表
     * @return BelongsTo
     */
    public function user(): BelongsTo
    {
        $module = static::getCalledModule();
        return $this->BelongsTo("app\\{$module}\\model\\User");
    }

    /**
     * 关联门店表
     * @return BelongsTo
     */
    public function shop(): BelongsTo
    {
        $module = static::getCalledModule();
        return $this->BelongsTo("app\\{$module}\\model\\store\\Shop", 'shop_id');
    }

    /**
     * 店员详情
     * @param $where
     * @return static|array|null
     */
    public static function detail($where)
    {
        return static::get($where);
    }
}
